package com.diandi.signature.controller.contract;


import com.diandi.signature.contract.SignatureContractService;
import com.diandi.signature.enums.fdd.ReturnCode;
import com.diandi.signature.enums.platfrom.ContractTypeAndTempName;
import com.diandi.signature.properties.FddProperties;
import com.diandi.signature.properties.SignatureProperties;
import com.diandi.signature.sign.SignUtil;
import com.diandi.signature.sign.Tools;
import com.diandi.signature.url.CreateTradeNo;
import com.diandi.signature.util.ContractUtil;
import com.diandi.signature.utils.CheckParams;
import com.diandi.signature.utils.GenViewMapTools;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 合同签章服务类
 * @author mwz
 * @create 2017-08-23 10:11
 * @version V1.0.0
 */
@Controller
@RequestMapping("/signatureContract")
public class SignatureContractController {
    private static Logger logger = LoggerFactory.getLogger(SignatureContractController.class);

    @Autowired
    private SignatureProperties signatureProperties;
    @Autowired
    private FddProperties fddProperties;

    @Autowired
    private SignatureContractService signatureContractService;

    @Autowired
    private ContractUtil contractUtil;
    /**
     * 合同签章
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/createSignatureContract")
    @ResponseBody
    public String CreateSignatureContract(HttpServletRequest request, HttpServletResponse response){
        /**
         * 1.1 接收业务端发送来的消息
         */
        Map<String,String> returnMap =  new HashMap<String,String>();
        String platTradeNo = CreateTradeNo.createTradeNo("TI");

        Long sp1 = System.currentTimeMillis();
        logger.info("--["+platTradeNo+"] createContract Start--");

        logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同创建]请求消息，开始处理--");
        Map<String, String> params = Tools.getParameterMap(request, false);
        try {
            logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同创建]requestMap:"+request.getRequestURL()+params+"--");
            returnMap = CheckParams.checkParamsIsExist(params, "userId","merchantNo","passCode","contractTitle","notifyUrl", "contractParams", "contractType");

            Long sp2 = System.currentTimeMillis();
            logger.info("--["+platTradeNo+"] step1 use times:"+(sp2-sp1)+"--");

            if (null != returnMap && !returnMap.isEmpty()) {
                logger.info("收到业务平台[合同创建]请求消息其中参数"+returnMap.toString()+"不能为空,返回给业务端,结束处理");
//                returnMap = Tools.createReturnParams(ReturnCode.err_1004,ReturnCode.err_1004.getMsg(),null);
                return Tools.createBusinessLinkString(returnMap,true,signatureProperties.getCharset());
            }

            logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同创建]: 校验业务平台参数正确--");

//            mongoService.insert("/signatureContract/createSignatureContract", "", params, platTradeNo, Long.parseLong(params.get("userId")), "", "请求报文");

            /**
             * 1.2 查询相关数据
             */
            returnMap = signatureContractService.createContract( request,platTradeNo);

            Long sp3 = System.currentTimeMillis();
            logger.info("--["+platTradeNo+"] step2 use times:"+(sp3-sp2)+"--");

            //生成签名
            String sign = SignUtil.signRSA(returnMap, signatureProperties.getPayPrivateSign(params.get("merchantNo")), signatureProperties.getCharset());
            logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同创建]: 生成签名完成--");
            returnMap.put("sign",sign);

            Long sp4 = System.currentTimeMillis();
            logger.info("--["+platTradeNo+"] step3 use times:"+(sp4-sp3)+"--");
//            mongoService.insert("/signatureContract/createSignatureContract", returnMap.toString(), params, platTradeNo, Long.parseLong(params.get("userId")), returnMap.get("msg"), "应答报文");
        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
            logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同创建]: 处理错误中断，返回:"+e.toString()+"--");
            returnMap = Tools.createReturnParams(ReturnCode.err,ReturnCode.err.getMsg(),null);
        }
        logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同创建]返回信息，结束处理--");

        logger.info("--["+platTradeNo+"] End createContract , TotalTimes:"+(System.currentTimeMillis()-sp1)+"--");

         return Tools.createLinkString(returnMap,true);
    }

    /**
     * 签章异步回调
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/callBack")
    @ResponseBody
    public String signatureCallBack(HttpServletRequest request, HttpServletResponse response) {


        String tradeNo = CreateTradeNo.createTradeNo("CCB");

        Long sp1 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] contractCallBack Start--");

        Map<String, String> requestMap = Tools.getParameterMap(request, false);
        Map<String, String> returnMap = new HashMap<String, String>();
        logger.info("收到异步通知消息requestMap:" + request.getRequestURL() + requestMap);
        String platTradeNo = requestMap.get("transaction_id");
        logger.info("--rcv:platTradeNo:" + platTradeNo + ":[合同签章-合同回调]: 开始合同回调处理--");
        returnMap = CheckParams.checkParamsIsExist(requestMap, "contract_id","transaction_id", "timestamp", "result_code", "result_desc", "msg_digest", "download_url", "viewpdf_url");

        Long sp2 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] step1 use times:"+(sp2-sp1)+"--");

        if (null != returnMap && !returnMap.isEmpty()) {
            logger.info("收到业务平台[合同创建]请求消息其中参数" + returnMap.toString() + "不能为空,返回给业务端,结束处理");
            return "error";
        }
        logger.info("--rcv:platTradeNo:" + platTradeNo + ":[合同签章-合同回调]: 结束合同回调处理--");

        logger.info("--["+tradeNo+"] End contractCallBack , TotalTimes:"+(System.currentTimeMillis()-sp1)+"--");

        return signatureContractService.ContractCallBack(platTradeNo, request);
    }

    /**
     * 合同预览接口
     * @param request
     * @return
     */
    @RequestMapping(value = "/viewContract")
    public ModelAndView viewContract(HttpServletRequest request){
        String platTradeNo = CreateTradeNo.createTradeNo("VN");

        Long sp1 = System.currentTimeMillis();
        logger.info("--["+platTradeNo+"] viewContract Start--");

        logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]请求消息: 开始处理--");
        Map<String, String> paramMap = Tools.getParameterMap(request, false);

        logger.debug("viewContract param is : [{}]", paramMap.toString());
        logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]请求消息--"+paramMap.toString());
        //如果合同类型为空，不处理
        if (!paramMap.containsKey("contractType")){
            logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]请求消息{合同类型为空}--"+paramMap.get("contractType")+"--结束处理--");
            return null;
        }

        Long sp2 = System.currentTimeMillis();
        logger.info("--["+platTradeNo+"] step1 use times:"+(sp2-sp1)+"--");

        String  returnUrl = ContractTypeAndTempName.getEnum(paramMap.get("contractType")).getJspName();

        ModelAndView mav = new ModelAndView(returnUrl);

        //判断是否有填充内容
        if (paramMap.containsKey("contractParams") && StringUtils.isNotBlank(paramMap.get("contractParams"))){
            logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]开始填充内容--"+paramMap.get("contractParams"));
//           Map genMap = FddContractSignatureTools.genContractParamMap(paramMap.get("contractType"), paramMap.get("contractParams"));
            Map<String, Object> genMap = GenViewMapTools.genContractParamMap(paramMap.get("contractType"), paramMap.get("contractParams"));
            mav.addObject("content", genMap);
        }
        Long sp3 = System.currentTimeMillis();
        logger.info("--["+platTradeNo+"] step2 use times:"+(sp3-sp2)+"--");
        logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]请求消息: 结束处理--");

        logger.info("--["+platTradeNo+"] End viewContract , TotalTimes:"+(System.currentTimeMillis()-sp1)+"--");
        return mav;
    }

    @RequestMapping(value = "/contract")
    @ResponseBody
    public String contract(HttpServletRequest request){
        /*Enumeration param = request.getParameterNames();
        while(param.hasMoreElements()){
            String paraName=(String)param.nextElement();
            System.out.println(paraName+": "+request.getParameter(paraName));
        }
        logger.info("参数为：param：--"+param);*/
        String platTradeNo = CreateTradeNo.createTradeNo("VN");

        Long sp1 = System.currentTimeMillis();
        logger.info("--["+platTradeNo+"] genViewUrl Start--");

        logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]请求消息: 开始处理--");

        Map<String, String> requestMap = Tools.getParameterMap(request, false);
        logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]请求消息参数--"+requestMap.toString());
        if (!requestMap.containsKey("contractType")){
            logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]请求消息{合同类型为空}--"+requestMap.get("contractType")+"--结束处理--");
            return null;
        }

        Long sp2 = System.currentTimeMillis();
        logger.info("--["+platTradeNo+"] step1 use times:"+(sp2-sp1)+"--");

        String contractType = requestMap.get("contractType");
        String contractParams = requestMap.get("contractParams");
        String url = contractUtil.getResultUrl();
        String result = url+"/signatureContract/viewContract"+"?contractType="+contractType;

        if (StringUtils.isNotBlank(contractParams)){
            result = result + "&contractParams="+contractParams;
        }

        Long sp3 = System.currentTimeMillis();
        logger.info("--["+platTradeNo+"] step2 use times:"+(sp3-sp2)+"--");

        logger.info("--rcv:platTradeNo:"+platTradeNo+":[合同预览]请求消息: 结束处理--");

        logger.info("--["+platTradeNo+"] End genViewUrl , TotalTimes:"+(System.currentTimeMillis()-sp1)+"--");

         return result;
    }
}